package com.ant.gateway.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 全局过滤器
 *
 * 外部请求通过网关请求内部服务
 * 外部请求到达网关时，向请求头中添加自定义请求头标识，告诉内部服务此请求来自网关
 */
@Component
public class GatewayGlobalFilter implements GlobalFilter, Ordered {

    static final Logger LOGGER = LoggerFactory.getLogger(GatewayGlobalFilter.class);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        LOGGER.info("=======进入全局过滤器=======");
        //设置自定义请求头
        //TODO 除登录、登出、注册等接口外，其余请求需要做token校验
        /**
         * 1、未登录，返回异常信息给前端，告知需要登录
         */
        exchange.getRequest().mutate().header("Custom-Head", "I'm gateway request!").build();
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 100;
    }
}
